// pages/handle-info/index.js
const App = getApp()

import moment from '../../utils/moment'
import Toast from '../../weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    api_root:'',
    currentIndex: 2,
    currentIndex2: '',
    currentIndex3: '',
    group_index: '',
    showIndex: "",
    show: false,
    show2: true,
    type: '',
    ratio: "",
    columns: [],
    columns_team: ['公池', '转出同事'],
    list: ['跟进记录', '带看预约', '成交数据', '客户转出'],
    ofent_list: ['正常维护', '下次继续', '未接电话'],
    activeNames: ['1'],
    members: [],
    level: "A",
    sale_type: "全款",
    team: "",
    content: "",
    time: "",
    help_member: '', //共同成交人姓名
    textarea_obj: {
      maxHeight: 300
    },
    deal_form: {
      customer_id: '',
      order_id:'',
      partner_id: '',
      partner_percent: '',
      project: '',
      house_id: '',
      paymethod: '全款',
      price_total: '',
      price_back: '',
      brokerage: '',
      channel: '',
      agent_name: '',
      agent_mobile: '',
      order_date: '',
      order_money: '',
      content: '',
      down_date: '',
      down_money: '',
      loan_date: '',
      loan_money: '',
      proof: ''
    },
    time_assign_type: '',
    submit_status: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    fileList: [],
    fileList2: [],
    fileList3: [],
    curIndex: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let api_root = wx.getStorageSync('api_root')
    if (api_root) {
      App.api_root = api_root;
    }
    options.curIndex == 1 ? this.data.list.splice(3, 1) : this.data.list
    this.getTeamList()
    this.getCustomerTurnover(options.id)
    this.setData({
      api_root: App.api_root,
      list: this.data.list,
      ...this.data.deal_form,
      'deal_form.order_id':options.orderid,
      'deal_form.customer_id': options.id
    })
  },
  //input数据绑定
  onInputChange(e) {
    console.log(e)
    let { str } = e.currentTarget.dataset
    let value = e.detail
    this.setData({
      [str]: value,
      deal_form: {
        ...this.data.deal_form,
        [str]: value
      }
    })
  },
  onChange(event) {
    // console.log(event)
    this.setData({
      activeNames: event.detail
    });
  },
  inputOnChange(e) {
    let input = e.currentTarget.dataset.input
    let value = e.detail
    this.setData({
      remind_form: {
        ...this.data.remind_form,
        [input]: value
      },
      follow_form: {
        ...this.data.follow_form,
        [input]: value
      },
      deal_form: {
        ...this.data.deal_form,
        [input]: value
      },
      rollout_form: {
        ...this.data.rollout_form,
        [input]: value
      },
    })
  },
  onConfirm(event) {
    console.log(event)
    let type = event.currentTarget.dataset.type
    let { value, index } = event.detail
    this.setData({
      [type]: value,
      show: false,
      deal_form: {
        ...this.data.deal_form,
        [type]: value
      },
    })
  },
  onConfirm2(event) {
    console.log(event)
    let type = event.currentTarget.dataset.type
    let { value, index } = event.detail
    if (index != 1) {
      this.setData({
        [type]: value,
        deal_form: {
          ...this.data.deal_form,
          [type]: value
        },
      })
    }
    console.log(this.data.deal_form)
    this.setData({
      show: index == 1,
      showIndex: index,
    })
  },

  onCancel() {
    this.setData({
      show: false
    })
  },
  onInput(event) {
    console.log(this.data.time_assign_type)
    this.setData({
      time: moment(event.detail).format("YYYY-MM-DD hh:mm:ss"),
      ...this.data.remind_form,
      ...this.data.follow_form,
      ...this.data.deal_form,
      'deal_form.order_date': this.data.time_assign_type == 'order_date' ? moment(event.detail).format("YYYY-MM-DD HH:mm:ss") : this.data.deal_form.order_date,
      'deal_form.down_date': this.data.time_assign_type == 'down_date' ? moment(event.detail).format("YYYY-MM-DD HH:mm:ss") : this.data.deal_form.down_date,
      'deal_form.loan_date': this.data.time_assign_type == 'loan_date' ? moment(event.detail).format("YYYY-MM-DD HH:mm:ss") : this.data.deal_form.loan_date,
      'remind_form.remind_time': this.data.time_assign_type == 'remind_time' ? moment(event.detail).format("YYYY-MM-DD HH:mm:ss") : this.data.remind_form.remind_time,
      'follow_form.remind_time': this.data.time_assign_type == 'remind_time' ? moment(event.detail).format("YYYY-MM-DD HH:mm:ss") : this.data.follow_form.remind_time
    });
  },
  //保存成员
  handleSaveMem(e) {
    this.setData({
      show: false
    })
  },
  //选择成员
  handleSelectMember(e) {
    console.log(e)
    const { value, type, index, findex, parid } = e.currentTarget.dataset
    this.setData({
      currentIndex3: index,
      [type]: value,
      group_index: findex,
      ...this.data.deal_form,
      ...this.data.rollout_form,
      'rollout_form.recipient_id': parid,
      'deal_form.partner_id': parid
    })
  },
  //选择常用内容
  handleSelctOfen(e) {
    let { value, index } = e.currentTarget.dataset
    this.setData({
      currentIndex2: index,
      content: value
    })
  },
  //等级框与日期框的切换
  handleInput(e) {
    let { type, input } = e.currentTarget.dataset
    let bol
    let arr
    console.log(e)
    switch (type) {
      case 'level':
        bol = 'level'
        arr = ['A', 'B', 'C', 'T', 'K', 'W']
        break;
      case 'time':
        bol = 'time'
        break;
      case 'coll':
        bol = 'coll'
        break;
      case 'roll':
        bol = 'roll'
        break;
      case 'paymethod':
        bol = 'paymethod'
        arr = ['全款', '贷款']
        break;
      default:
        break;
    }
    this.setData({
      show: true,
      show2: false,
      showIndex: '',
      columns: arr,
      type: bol,
      time_assign_type: input
    })
  },
  //切换头部tabs
  handleTabS(e) {
    let time1 = new Date().getTime() + 24 * 60 * 60 * 1000
    let time2 = new Date().getTime()
    this.setData({
      ...this.data.follow_form,
      ...this.data.remind_form,
      'follow_form.remind_time': '',
      'remind_form.remind_time': '',
      currentIndex: e.currentTarget.dataset.index,
      currentIndex3: '',
      group_index: '',
      minDate: this.data.currentIndex == 0 ? time1 : time2
    })
    console.log(this.data.currentIndex)
  },

  handleSaveForm() {
    if (this.data.deal_form.paymethod == '全款') {
      this.setData({
        ...this.data.deal_form,
        'deal_form.paymethod': 0,
      })
    } else {
      this.setData({
        ...this.data.deal_form,
        'deal_form.paymethod': 1,
      })
    }
    let _this = this
    delete _this.data.deal_form.proof_arr
    _this.data.deal_form.proof = _this.data.deal_form.proof.split(',')
    _this.data.deal_form.proof = _this.data.deal_form.proof.map(item => {
      return item.replace('https://p.t.fangx999.com','')
    });
    _this.data.deal_form.proof = _this.data.deal_form.proof.join(',')
    _this.setData({
      deal_form: _this.data.deal_form,
      'deal_form.proof':_this.data.deal_form.proof
    })
    console.log(_this.data.deal_form)
    App._post_form('customer/customerTurnover', _this.data.deal_form, function (result) {
      if (result.code === 0) {
        Toast({
          type: 'success',
          message: '提交成功',
          onClose: () => {
            wx.redirectTo({
              url: './index',
            })
          },
        });
      } else {
        Toast.fail(result.msg);
      }
    });
  },

  //查看客户成交数据
  getCustomerTurnover(id) {
    let _this = this
    App._post_form('Customer/getCustomerTurnover', {
      order_id: id
    }, function (result) {
      let arr = []
      let ts = ''
      let meth = ''
      _this.data.members.forEach(item => {
        item.list.forEach(v => {
          console.log(v)
          arr.push(v)
        })
      });
      arr.forEach(item => {
        if (item.id == result.data.partner_id) {
          ts = item.name
        }
      });
      if (result.data.paymethod == 0) {
        console.log('1111')
        meth = '全款'
      } else {
        meth = '贷款'
      }
      let arr_list = []
      let arr_list2 = []
      let arr_list3 = []
      console.log(result.data.proof_arr)
      result.data.proof_arr.forEach(item => {
        if (item.indexOf('https') == -1) {
          arr_list.push({
            url: _this.data.api_root + `${item}`
          })
        } else {
          arr_list.push({
            url: item
          })
        }
      });

      result.data.proof2_arr.forEach(item => {
        if (item.indexOf('https') == -1) {
          arr_list2.push({
            url: _this.data.api_root + `${item}`
          })
        } else {
          arr_list2.push({
            url: item
          })
        }
      });
      result.data.proof3_arr.forEach(item => {
        if (item.indexOf('https') == -1) {
          arr_list3.push({
            url: _this.data.api_root + `${item}`
          })
        } else {
          arr_list3.push({
            url: item
          })
        }
      });
      _this.setData({
        help_member: ts,
        deal_form: result.data,
        'deal_form.paymethod': meth,
        fileList: arr_list,
        fileList2: arr_list2,
        fileList3: arr_list3
      })
      console.log(_this.data.fileList)
    });
  },
  //获取团队数据
  getTeamList() {
    let _this = this
    App._post_form('Member/getTeamList', {},
      function (result) {
        _this.setData({
          members: result.data
        })
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //图片上传
  afterRead(event) {
    const { file } = event.detail;
    // file.name = event.detail.name

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let _this = this
    let imgList = []
    wx.uploadFile({
      url: 'https://p.t.fangx999.com/Customer/imageUpload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'proof',
      success(res) {
        console.log(res)
        let arr_list = []
        const { fileList = [] } = _this.data;
        fileList.forEach(item => {
          arr_list.push(item)
        });
        fileList.push({ ...file, url: JSON.parse(res.data).data.url });
        arr_list.push({ ...file, url: JSON.parse(res.data).data.url });
        imgList = arr_list.map(item => {
          return item.url
        })
        imgList = imgList.join(',')
        console.log(imgList)
        _this.setData({
          ..._this.data.deal_form,
          'deal_form.proof': imgList,
          fileList
        });
      },
    });
  },
  //删除
  deleteImg(e) {
    const index = e.detail.index
    let imgList = []
    this.data.fileList.splice(index, 1)
    imgList = this.data.fileList.map(item => {
      return item.url
    })
    imgList = imgList.join(',')
    console.log(imgList)
    this.setData({
      fileList: this.data.fileList,
      ...this.data.deal_form,
      'deal_form.proof': imgList
    })
    console.log(e, this.data.fileList)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})